<script setup>
import businessFlowService from '@/api/businessFlow/index.js'
import businessInterfaceService from '@/api/businessInterface/index.js'
import businessFlowMenuService from '@/api/system/businessFlowMenu.js'
import { listRole } from '@/api/system/role.js'
import CodeEditor from '@/components/CodeEditor/CodeEditor.vue'
import SearchBar from '@/components/SearchBar/SearchBar.vue'
import { useDict } from '@/utils/dict.js'
import { deepClone } from '@/utils/index.js'
import { flowDefaultData, themeApprove } from '@/views/system/businessFlow/flowConfig.js'

import '@logicflow/core/dist/index.css'

import FlowNodePanel from '@/views/system/businessFlow/components/FlowNodePanel/FlowNodePanel.vue'
import RegisteNode from '@/views/system/businessFlow/registerNode.js'
import FlowControl from '@/views/system/businessFlow/components/FlowControl/FlowControl.vue'
import { Plus } from '@element-plus/icons-vue'
import LogicFlow from '@logicflow/core'
import '@logicflow/extension/lib/style/index.css'
import { Menu } from '@logicflow/extension'
import Message from 'vue-m-message'
import { useRoute, useRouter } from 'vue-router'

LogicFlow.use(Menu)

const businessFlowData = ref({
  flowName: '',
  menuList: [],
})
const lf = ref(null)
const drawerVisible = ref(false)
const setupFormData = ref({
  afterInterfaceId: null,
  isDecideNode: '1',
})
const config = {
  stopScrollGraph: true,
  stopZoomGraph: true,
  grid: {
    size: 10,
    visible: true,
    type: 'mesh',
    config: {
      color: '#DCDCDC',
    },
  },
  style: themeApprove,
}
const flowMenList = ref([])
const stepList = ref([])
const { step_type, sys_flow_audit_status } = useDict('step_type', 'sys_flow_audit_status')
const nextStepOptions = ref([])
const roleOptions = ref([])
const setupFormDataRules = reactive({})
const stepOrderOptions = computed(() => {
  return stepList.value.map(item => ({
    label: item.stepOrder,
    value: item.stepOrder,
  }))
})
const interfaceVisible = ref(false)
const afterInterfaceSearchConfig = reactive([
  {
    label: '所属流程',
    field: 'flowId',
    type: 'input',
  },
  {
    label: '接口名称',
    field: 'interfaceName',
    type: 'input',
  },
])
const afterInterfaceQueryParam = ref({})
const interfacePagerConfig = ref({
  total: 0,
  currentPage: 1,
  pageSize: 10,
})
const interfaceTableData = ref([])
const interfaceTableColumns = ref([
  { type: 'radio', width: 50 },
  {
    field: 'flowId',
    title: '所属流程',
    align: 'center',
    showOverflow: 'tooltip',
  },
  {
    field: 'interfaceName',
    title: '接口名称',
    align: 'center',
    showOverflow: 'tooltip',
  },
  {
    field: 'remark',
    title: '备注',
    align: 'center',
    minWidth: 10,
    showOverflow: 'tooltip',
  },
])
const interfaceType = ref('')
const interfaceTable = ref(null)
const interfaceBranchIndex = ref(0)
const stepBranchMap = {
  1: [
    {
      customRelateJudge: '${db.sys_contract.audit_status}=',
      isDefaultBranch: '0',
      branchOrder: '',
      branchName: '',
      nextStep: '',
    },
    {
      customRelateJudge: '${db.sys_contract.audit_status}=',
      isDefaultBranch: '1',
      branchOrder: '',
      branchName: '',
      nextStep: '',
    },
  ],
  4: [
    {
      customRelateJudge: '${db.sys_contract.is_big_contract}=',
      isDefaultBranch: '0',
      branchOrder: '',
      branchName: '',
      branchAfterInterfaceId: '',
      nextStep: '',
    },
    {
      customRelateJudge: '${db.sys_contract.is_big_contract}=',
      isDefaultBranch: '1',
      branchOrder: '',
      branchName: '',
      branchAfterInterfaceId: '',
      nextStep: '',
    },
  ],
}
const router = useRouter()
const route = useRoute()
const { flowId, type } = route.query
const customBtnTypeOptions = reactive([
  {
    label: '新增',
    value: 'add',
  },
  {
    label: '删除',
    value: 'delete',
  },
])
const interFaceRadioData = ref({})
onMounted(() => {
  if (flowId) {
    handleGetBusinessDetail()
  }
  handleSetBusinessFlowContainer()
  handleGetBusinessFlowData()
})

function handleGetBusinessDetail() {
  businessFlowService.detail(flowId).then((res) => {
    const { data } = res
    businessFlowData.value = data
    businessFlowData.value.menuList = data.menuList[0].menuId
    const flowData = {
      edges: JSON.parse(data.edges),
      nodes: JSON.parse(data.nodes),
    }
    lf.value.render(flowData)
    stepList.value = data.stepList
    stepList.value.forEach((item) => {
      item.roleId = item.stepRoleList.map(item => item.roleId)
      delete item.stepRoleList
      if (item.nextStep === -1) {
        item.nextStep = null
      }
    })
    getInterfaceData()
  })
}
function handleSetBusinessFlowContainer() {
  const logicFlow = new LogicFlow({
    ...config,
    container: document.querySelector('#graph'),
    keyboard: {
      enabled: true,
    },
    isSilentMode: type === 'view',
  })
  logicFlow.setTheme(
    {
      nodeText: { overflowMode: 'autoWrap', lineHeight: 1.5 },
      edgeText: { overflowMode: 'autoWrap', lineHeight: 1.5 },
    },
  )
  lf.value = logicFlow

  RegisteNode(logicFlow)
  lf.value.render(flowDefaultData)
  initEvent(logicFlow)
}

function getInterfaceData() {
  const params = {
    ...afterInterfaceQueryParam.value,
    pageNum: interfacePagerConfig.value.currentPage,
    pageSize: interfacePagerConfig.value.pageSize,
  }
  businessInterfaceService.list(params).then((res) => {
    interfaceTableData.value = res.rows
    interfacePagerConfig.value.total = res.total
  })
}

function initEvent(lf) {
  const graphData = lf.getGraphData()
  const nodes = graphData.nodes

  if (nodes.length > 0) {
    stepList.value = handleSetSetupList(nodes)
  }

  lf.on('node:click', (event) => {
    const { data } = event
    const step = stepList.value.find(item => item.stepNodeId === data.id)
    const nextFilter = stepList.value.filter(item => item.stepNodeId !== data.id)
    if (step) {
      setupFormData.value = {
        ...setupFormData.value,
        ...step,
        isDecideNode: step.isDecideNode || '1',
        stepName: data.text?.value || '',
        stepStatusName: data.text?.value || '',
        stepBranchList: step.stepBranchList || stepBranchMap[step.stepType],
      }
      nextStepOptions.value = nextFilter.filter(item => item.stepName !== '开始')
      setupFormData.value.stepBranchList?.forEach((item) => {
        // item.nextStep = item.isDefaultBranch === '0' ? step.nextStep : null
        if (item.isDefaultBranch === '0') {
          item.nextStep = step.nextStep === null ? null : item.nextStep || step.nextStep
        }
      })
    }
    else {
      console.error('没有找到该步骤')
    }
    if (data.text?.value !== '开始' && data.text?.value !== '结束') {
      drawerVisible.value = true
    }
    // nextTick(() => {
    //   console.log(interfaceTable.value)
    //   interfaceTable.value.clearCheckboxRow()
    // })
  })

  lf.on('history:change', () => {
    const historyChangeGraphData = lf.getGraphData()
    const historyChangeGraphDataNodes = historyChangeGraphData.nodes
    stepList.value = handleSetSetupList(historyChangeGraphDataNodes)
  })
}

function handleGetBusinessFlowData() {
  businessFlowMenuService.queryChildrenMenu().then((res) => {
    const { data } = res
    flowMenList.value = data
  })
  listRole().then((res) => {
    roleOptions.value = res.rows
  })
}

/**
 * @title 设置setupList 默认值
 * @description 如果setupList要添加默认值就在这个函数操作
 * @param {Array} nodes - 节点数组
 * @returns {Array} 设置好的步骤列表
 */
function handleSetSetupList(nodes) {
  const steps = stepList.value
  if (!steps.length) {
    return nodes.map((node, index) => ({
      stepOrder: index,
      stepName: node.text?.value || '未知步骤',
      stepStatusName: node.text?.value || '',
      stepNodeId: node.id,
      isSkNode: '1',
    }))
  }
  const graphData = lf.value.getGraphData()

  graphData.edges?.forEach((node) => {
    nodes.forEach((item) => {
      if (item.id === node.sourceNodeId) {
        const nextStep = stepList.value.find(item => item.stepNodeId === node.sourceNodeId)?.nextStep
        const stepOrder = stepList.value.find(item => item.stepNodeId === node.targetNodeId)?.stepOrder
        if (!nextStep) {
          item.nextStep = stepOrder
        }
        else {
          item.nextStep = nextStep
        }
      }
    })
  })
  return nodes.map((node) => {
    const matchedStep = steps.find(s => s.stepNodeId === node.id)
    const defaultStep = matchedStep
      ? {
          ...matchedStep,
          nextStep: node.nextStep || null,
          stepName: node.text?.value || '未知步骤',
          stepStatusName: node.text?.value || '',
        }
      : null
    const stepData = defaultStep || {
      stepOrder: nodes.indexOf(node),
      stepName: node.text?.value || '未知步骤',
      stepStatusName: node.text?.value || '',
      stepNodeId: node.id,
      isSkNode: '1',
      nextStep: node.nextStep || null,
    }
    return {
      ...stepData,
    }
  })
}

function handleChangeSetupList(type = '') {
  const object = setupFormData.value
  console.log(object)
  const step = stepList.value.find(item => item.stepNodeId === object.stepNodeId)
  if (!step) {
    console.error('没有找到该步骤')
    return
  }
  if (type === 'name') {
    lf.value.graphModel.updateText(step.stepNodeId, object.stepName)
  }
  if (type === 'select') {
    const keysToKeep = ['stepOrder', 'stepName', 'stepStatus', 'nextStep', 'isSkNode', 'stepType', 'stepNodeId', 'stepStatusName', 'roleId', 'menuId', 'isDecideNode', 'afterInterfaceId']
    // 选择操作的时候 清空除了指定字段之外的所有其他字段
    setupFormData.value = Object.keys(object)
      .filter(key => keysToKeep.includes(key))
      .reduce((obj, key) => {
        obj[key] = object[key]
        return obj
      }, {})
    if (object.stepType === '1') {
      const findFailureStep = stepList.value.find(item => item.nextStep === object.stepOrder)
      object.failureStep = findFailureStep?.stepOrder
    }
    if (object.stepType === '2') {
      setupFormData.value.fileSuffixRegular = '.*'
      setupFormData.value.fileSize = '<5m'
    }
    if (object.stepType === '1' || object.stepType === '4') {
      setupFormData.value.stepBranchList = stepBranchMap[object.stepType]
      setupFormData.value.stepBranchList.forEach((item) => {
        if (item.isDefaultBranch === '0' && step.nextStep) {
          item.nextStep = step.nextStep
          item.branchOrder = step.nextStep + Math.floor(Math.random() * 50) + 100
        }
      })
      console.log(setupFormData.value)
    }
  }
  if (object.stepType === '3') {
    console.log(setupFormData.value.customName)
    if (setupFormData.value.customName) {
      setupFormData.value.customTips = `是否确认${setupFormData.value.customName}？`
    }
  }
  console.log(object)
  Object.keys(object).forEach((key) => {
    step[key] = object[key]
  })
}

function handleDrawerClosed() {
  setupFormData.value = {}
  drawerVisible.value = false
}

function handleAddInterface(type, index = 0) {
  getInterfaceData()
  interfaceType.value = type
  interfaceBranchIndex.value = index
  interfaceVisible.value = true
  nextTick(() => {
    const $interfaceTable = interfaceTable.value
    let id = ''
    $interfaceTable?.clearRadioRow()
    if (type === 'after') {
      id = setupFormData.value.afterInterfaceId
    }
    if (type === 'before') {
      id = setupFormData.value.branchBeforeInterfaceId
    }
    if (type === 'branch') {
      id = setupFormData.value.stepBranchList[index].branchAfterInterfaceId
    }
    if (id) {
      const findData = interfaceTableData.value.find(item => id.includes(item.interfaceId))
      $interfaceTable.setRadioRow(findData, true)
    }
  })
}

function handleAfterInterfaceRadioChange(data) {
  // if (interfaceType.value === 'before') {
  //   setupFormData.value.branchBeforeInterfaceId = data.rowid
  // }
  // if (interfaceType.value === 'after') {
  //   setupFormData.value.afterInterfaceId = data.rowid
  // }
  // if (interfaceType.value === 'branch') {
  //   setupFormData.value.stepBranchList[interfaceBranchIndex.value].branchAfterInterfaceId = data.rowid
  // }
  interFaceRadioData.value = data
}

function handleSureInterface() {
  if (interfaceType.value === 'before') {
    setupFormData.value.branchBeforeInterfaceId = interFaceRadioData.value.rowid
  }
  if (interfaceType.value === 'after') {
    setupFormData.value.afterInterfaceId = interFaceRadioData.value.rowid
  }
  if (interfaceType.value === 'branch') {
    setupFormData.value.stepBranchList[interfaceBranchIndex.value].branchAfterInterfaceId = interFaceRadioData.value.rowid
  }
  interfaceVisible.value = false
  handleChangeSetupList()
}

function handleInterfaceTablePageChange({ currentPage, pageSize }) {
  interfacePagerConfig.value.currentPage = currentPage
  interfacePagerConfig.value.pageSize = pageSize
  getInterfaceData()
}

function handleInterfaceSearch(e) {
  afterInterfaceQueryParam.value = e
  getInterfaceData()
}

function handleInterfaceVisibleClose() {
  afterInterfaceQueryParam.value = {}
  interfacePagerConfig.value.currentPage = 1
  interfacePagerConfig.value.pageSize = 10
  interfaceVisible.value = false
}

function handleActionBranch(type, index) {
  if (type === 'add') {
    setupFormData.value.stepBranchList.push({
      customRelateJudge: '',
      isDefaultBranch: '1',
      branchName: '',
      branchOrder: '',
      branchAfterInterfaceId: '',
    })
  }
  else {
    setupFormData.value.stepBranchList.splice(index, 1)
  }
}

function handleSubmitFlow() {
  const cloneStepList = deepClone(stepList.value)
  const lfData = lf.value.getGraphData()
  console.log(lfData)
  const {
    flowName,
    menuList,
  } = businessFlowData.value
  if (flowName === '' && menuList.length === 0) {
    Message.error('请填写流程名称和菜单')
    return
  }
  cloneStepList.forEach((item) => {
    item.stepRoleList = item.roleId ? item.roleId.map(id => ({ roleId: id })) : []
    delete item.roleId
    // 判断最后一个的step 是不是空值，如果是空值，则把step默认设置成-1
    if (item.stepOrder === cloneStepList.length - 1 && !item.nextStep) {
      item.nextStep = -1
    }
    // 判断 nextSt有没有值 以及 存不存在 -1
    // if (!item.nextStep && item.nextStep !== -1) {
    //   item.nextStep = -1
    // }
    item.stepBranchList?.forEach((branch) => {
      if (branch.branchOrder === '' && branch.nextStep) {
        branch.branchOrder = branch.nextStep + Math.floor(Math.random() * 50) + 100
      }
      // branch.branchAfterInterfaceId = branch.branchAfterInterfaceId?.length > 0 ? branch.branchAfterInterfaceId.join(',') : null
    })
    // item.afterInterfaceId = item.afterInterfaceId?.length > 0 ? item.afterInterfaceId.join(',') : null
    if (item.stepType !== '1' && item.stepType !== '4') {
      item.stepBranchList = null
    }
    // item.menuId = item.menuId?.[0]
  })
  const params = {
    flowName,
    edges: JSON.stringify(lfData.edges),
    nodes: JSON.stringify(lfData.nodes),
    menuList: [
      {
        menuId: menuList,
      },
    ],
    stepList: cloneStepList,
    flowStyle: '案件流程样式',
  }
  if (flowId) {
    params.flowId = flowId
    businessFlowService.update(params).then((res) => {
      const code = res.code
      if (code === 200) {
        Message.success('修改成功')
      }
    })
  }
  else {
    businessFlowService.insert(params).then((res) => {
      const code = res.code
      if (code === 200) {
        Message.success('提交成功')
        drawerVisible.value = false
        router.push({ path: '/business/businessFlow' })
      }
      else {
        Message.error('提交失败')
      }
    })
  }
}

function handleGetInterfaceName(val) {
  const name = interfaceTableData.value.find(item => item.interfaceId === val)?.interfaceName
  return name
}

function handleInterfaceClearSelect() {
  if (interfaceType.value === 'before') {
    setupFormData.value.branchBeforeInterfaceId = ''
  }
  if (interfaceType.value === 'after') {
    setupFormData.value.afterInterfaceId = ''
  }
  if (interfaceType.value === 'branch') {
    setupFormData.value.stepBranchList[interfaceBranchIndex.value].branchAfterInterfaceId = ''
  }
  const $interfaceTable = interfaceTable.value
  $interfaceTable.clearRadioRow()
  interFaceRadioData.value = {}
}
</script>

<template>
  <div class="p-2 relative flow-container">
    <el-card header="基本信息" class="mb-3" shadow="never">
      <div class="grid grid-cols-2 gap-5">
        <div class="flex-center">
          <div class="w-20">
            流程名称:
          </div>
          <el-input v-model="businessFlowData.flowName" placeholder="请输入" :disabled="type === 'view'" />
        </div>
        <div class="flex-center">
          <div class="w-20">
            指定菜单:
          </div>
          <!--          <el-cascader -->
          <!--            v-model="businessFlowData.menuList" -->
          <!--            :options="flowMenList" -->
          <!--            :props="{ -->
          <!--              label: 'fatherName', -->
          <!--              value: 'fatherId', -->
          <!--              key: 'fatherId', -->
          <!--              children: 'childrenMenu', -->
          <!--            }" -->
          <!--            class="w-full" -->
          <!--          /> -->
          <el-select
            v-model="businessFlowData.menuList" placeholder="请选择" clearable filterable
            :disabled="type === 'view'"
          >
            <el-option
              v-for="item in flowMenList"
              :key="item.fatherId"
              :label="item.fatherName"
              :value="item.fatherId"
            />
          </el-select>
        </div>
      </div>
    </el-card>
    <div class="relative h-full">
      <FlowControl v-if="lf" :lf="lf" class="absolute top-5 right-1 z-10">
        <template #button>
          <el-button type="primary" :disabled="!stepList.length || type === 'view'" @click="handleSubmitFlow">
            提交流程
            <el-icon class="ml-1">
              <CirclePlusFilled />
            </el-icon>
          </el-button>
        </template>
      </FlowControl>
      <div class="node-panel">
        <FlowNodePanel :lf="lf" />
      </div>
      <div id="graph" class="viewport" />
      <el-drawer
        v-model="drawerVisible"
        title="步骤设置"
        class="flow-add__drawer"
        :show-close="false"
        :close-on-click-modal="false"
        @closed="handleDrawerClosed"
      >
        <template #header>
          <div class="dialog-header">
            <span class="relative top-3 text-[16px] ">
              新增业务流程
            </span>
          </div>
        </template>
        <el-form
          :model="setupFormData"
          :rules="setupFormDataRules"
          class="mt-5 px-1"
          label-width="100px"
        >
          <el-form-item label="流程序号">
            <el-select
              v-model="setupFormData.stepOrder" placeholder="请选择" clearable filterable disabled
              @change="handleChangeSetupList('selectOrder')"
            >
              <el-option
                v-for="item in stepOrderOptions"
                :key="item.value"
                :label="item.label"
                :value="item.label"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="步骤名称">
            <el-input v-model="setupFormData.stepName" placeholder="请输入" @input="handleChangeSetupList('name')" />
          </el-form-item>
          <el-form-item label="是否判断节点">
            <el-segmented
              v-model="setupFormData.isDecideNode" :options="[
                {
                  label: '是',
                  value: '0',
                },
                {
                  label: '否',
                  value: '1',
                },
              ]"
              @change="handleChangeSetupList()"
            />
          </el-form-item>
          <template v-if="setupFormData.isDecideNode === '1'">
            <el-form-item label="状态">
              <el-input
                v-model="setupFormData.stepStatusName" placeholder="请输入"
                @input="handleChangeSetupList('name')"
              />

              <!--            <el-select v-model="setupFormData.stepStatus" placeholder="请选择" clearable @change="handleChangeSetupList()"> -->
              <!--              <el-option -->
              <!--                v-for="dict in sys_flow_audit_status" -->
              <!--                :key="dict.value" -->
              <!--                :label="dict.label" -->
              <!--                :value="dict.value" -->
              <!--              /> -->
              <!--            </el-select> -->
            </el-form-item>
            <el-form-item label="步骤值">
              <el-select
                v-model="setupFormData.stepStatus" placeholder="请选择步骤值" clearable filterable
                @input="handleChangeSetupList()"
              >
                <el-option
                  v-for="dict in step_type"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                />
              </el-select>
            </el-form-item>
            <el-form-item label="指定角色">
              <el-select
                v-model="setupFormData.roleId" placeholder="请选择指定角色" clearable filterable multiple
                @change="handleChangeSetupList()"
              >
                <el-option
                  v-for="item in roleOptions"
                  :key="item.roleId"
                  :label="item.roleName"
                  :value="item.roleId"
                />
              </el-select>
            </el-form-item>
            <el-form-item label="指定菜单">
              <!--              <el-cascader -->
              <!--                v-model="setupFormData.menuId" -->
              <!--                :options="flowMenList" -->
              <!--                :props="{ -->
              <!--                  label: 'fatherName', -->
              <!--                  value: 'fatherId', -->
              <!--                  key: 'fatherId', -->
              <!--                  children: 'childrenMenu', -->
              <!--                }" -->
              <!--                class="w-full" -->
              <!--                @change="handleChangeSetupList()" -->
              <!--              /> -->
              <el-select
                v-model="setupFormData.menuId" placeholder="请选择" clearable filterable class="w-full"
                @change="handleChangeSetupList()"
              >
                <el-option
                  v-for="item in flowMenList"
                  :key="item.fatherId"
                  :label="item.fatherName"
                  :value="item.fatherId"
                />
              </el-select>
            </el-form-item>
            <el-form-item label="是否收款节点">
              <el-segmented
                v-model="setupFormData.isSkNode"
                :options="[
                  {
                    label: '是',
                    value: '0',
                  },
                  {
                    label: '否',
                    value: '1',
                  },
                ]"
                @change="handleChangeSetupList()"
              />
            </el-form-item>
          </template>
          <el-form-item label="下一步">
            <el-select
              v-model="setupFormData.nextStep" placeholder="请选择" clearable
              @change="handleChangeSetupList()"
            >
              <el-option
                v-for="item in nextStepOptions"
                :key="item.stepOrder"
                :label="item.stepName"
                :value="item.stepOrder"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="后置接口" prop="afterInterface">
            <el-button type="primary" size="small" @click="handleAddInterface('after')">
              添加
              <el-icon class="ml-1">
                <CirclePlusFilled />
              </el-icon>
            </el-button>
            <div v-if="setupFormData.afterInterfaceId" class="ml-2">
              - {{ handleGetInterfaceName(setupFormData.afterInterfaceId) }}
            </div>
          </el-form-item>
          <el-form-item label="操作">
            <el-select
              v-model="setupFormData.stepType" placeholder="请选择" clearable
              @change="handleChangeSetupList('select')"
            >
              <el-option
                v-for="dict in step_type"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
              />
            </el-select>
          </el-form-item>
          <div
            v-if="setupFormData.stepType && setupFormData.stepType !== '5' && setupFormData.stepType !== '7'"
            class="business-custom-page p-5 rounded-md"
          >
            <template v-if="setupFormData.stepType === '1'">
              <template v-for="(item, index) in setupFormData.stepBranchList.slice(0, 2)" :key="index">
                <template v-if="item.isDefaultBranch === '0'">
                  <el-form-item label="默认分支">
                    <el-input
                      v-model="item.branchName" placeholder="请输入默认分支" clearable
                      @input="handleChangeSetupList()"
                    />
                  </el-form-item>
                  <el-form-item label="默认步骤">
                    <el-select v-model="item.nextStep" placeholder="请选择默认步骤" clearable filterable>
                      <el-option
                        v-for="item in nextStepOptions"
                        :key="item.stepOrder"
                        :label="item.stepName"
                        :value="item.stepOrder"
                      />
                    </el-select>
                  </el-form-item>
                </template>
                <template v-if="item.isDefaultBranch === '1'">
                  <el-form-item label="其他分支">
                    <el-input
                      v-model="item.branchName" placeholder="请输入分支名称" clearable
                      @input="handleChangeSetupList()"
                    />
                  </el-form-item>
                  <el-form-item label="其他分支步骤">
                    <el-select v-model="item.nextStep" placeholder="请选择其他分支步骤" clearable filterable>
                      <el-option
                        v-for="item in nextStepOptions"
                        :key="item.stepOrder"
                        :label="item.stepName"
                        :value="item.stepOrder"
                      />
                    </el-select>
                  </el-form-item>
                </template>
                <el-form-item label="分支判断条件">
                  <CodeEditor
                    v-model="item.customRelateJudge"
                    lang="java"
                    class="w-full h-[28px]"
                  />
                </el-form-item>
              </template>
            </template>
            <template v-if="setupFormData.stepType === '2'">
              <el-form-item label="上传文件后缀正则" prop="fileSuffixRegular" label-width="130px">
                <el-input
                  v-model="setupFormData.fileSuffixRegular" placeholder="请输入上传文件后缀正则" clearable
                  @input="handleChangeSetupList()"
                />
              </el-form-item>
              <el-form-item label="上传文件大小" label-width="130px">
                <el-input
                  v-model="setupFormData.fileSize" placeholder="请输入上传文件大小限制" clearable
                  @input="handleChangeSetupList()"
                />
              </el-form-item>
              <el-form-item label="文件内容识别正则" label-width="130px">
                <el-input
                  v-model="setupFormData.fileContentIdentify" placeholder="请输入文件内容识别正则" clearable
                  @input="handleChangeSetupList()"
                />
              </el-form-item>
              <el-form-item label="最多允许" label-width="130px">
                <el-input
                  v-model="setupFormData.maxAllowCount" placeholder="" clearable
                  @input="handleChangeSetupList()"
                />
              </el-form-item>
            </template>
            <template v-if="setupFormData.stepType === '3'">
              <el-form-item label="自定义名称">
                <el-input
                  v-model="setupFormData.customName" placeholder="请输入自定义名称" clearable
                  @input="handleChangeSetupList()"
                />
              </el-form-item>
              <el-form-item label="自定义提示">
                <el-input
                  v-model="setupFormData.customTips" placeholder="请输入自定义提示" clearable
                  @input="handleChangeSetupList()"
                />
              </el-form-item>
              <el-form-item label="按钮类型">
                <el-select
                  v-model="setupFormData.customBtnType" placeholder="请输入按钮类型" clearable
                  @input="handleChangeSetupList()"
                >
                  <el-option
                    v-for="item in customBtnTypeOptions"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                  />
                </el-select>
              </el-form-item>
            </template>
            <template v-if="setupFormData.stepType === '4'">
              <el-form-item label="分支名称">
                <el-input
                  v-model="setupFormData.branchName" placeholder="请输入分支名称" clearable
                  @input="handleChangeSetupList()"
                />
              </el-form-item>
              <el-form-item label="前置判断条件">
                <CodeEditor
                  v-model="setupFormData.branchBeforeDecide"
                  lang="java"
                  class="w-full h-[28px]"
                />
              </el-form-item>
              <el-form-item label="前置接口">
                <el-button type="primary" size="small" @click="handleAddInterface('before')">
                  添加
                  <el-icon class="ml-1">
                    <CirclePlusFilled />
                  </el-icon>
                </el-button>
                <div v-if="setupFormData.branchBeforeInterfaceId" class="ml-3">
                  - {{ handleGetInterfaceName(setupFormData.branchBeforeInterfaceId) }}
                </div>
              </el-form-item>
              <template v-for="(item, index) in setupFormData.stepBranchList" :key="index">
                <div class="my-3 flex-x-between">
                  <div class="font-500">
                    {{ item.isDefaultBranch === '0' ? '默认分支' : `其他分支${index}` }}
                  </div>
                  <div v-if="item.isDefaultBranch === '1'">
                    <el-button
                      type="primary" size="small" title="添加其他分支" circle plain
                      @click="handleActionBranch('add', index)"
                    >
                      <el-icon>
                        <Plus />
                      </el-icon>
                    </el-button>
                    <el-button
                      type="danger" size="small" title="删除分支" circle plain
                      :disabled="setupFormData.stepBranchList.length === 2"
                      @click="handleActionBranch('del', index)"
                    >
                      <el-icon>
                        <Delete />
                      </el-icon>
                    </el-button>
                  </div>
                </div>
                <el-form-item label="分支判断条件">
                  <CodeEditor
                    v-model="item.customRelateJudge"
                    lang="java"
                    class="w-full h-[28px]"
                  />
                </el-form-item>
                <span v-if="item.isDefaultBranch === '0'">

                  <el-form-item label="默认分支">
                    <el-input
                      v-model="item.branchName" placeholder="请输入默认分支" clearable
                      @input="handleChangeSetupList()"
                    />
                  </el-form-item>
                  <el-form-item label="默认步骤">
                    <el-select v-model="item.nextStep" placeholder="请选择默认步骤" clearable filterable>
                      <el-option
                        v-for="item in nextStepOptions"
                        :key="item.stepOrder"
                        :label="item.stepName"
                        :value="item.stepOrder"
                      />
                    </el-select>
                  </el-form-item>
                </span>
                <span v-if="item.isDefaultBranch === '1'">
                  <el-form-item label="其他分支">
                    <el-input
                      v-model="item.branchName" placeholder="请输入分支名称" clearable
                      @input="handleChangeSetupList()"
                    />
                  </el-form-item>
                  <el-form-item label="其他分支步骤">
                    <el-select v-model="item.nextStep" placeholder="请选择其他分支步骤" clearable filterable>
                      <el-option
                        v-for="item in nextStepOptions"
                        :key="item.stepOrder"
                        :label="item.stepName"
                        :value="item.stepOrder"
                      />
                    </el-select>
                  </el-form-item>
                </span>
                <el-form-item label="分支接口">
                  <el-button type="primary" size="small" @click="handleAddInterface('branch', index)">
                    添加
                    <el-icon class="ml-1">
                      <CirclePlusFilled />
                    </el-icon>
                  </el-button>
                  <div v-if="item.branchAfterInterfaceId" class="ml-2">
                    - {{ handleGetInterfaceName(item.branchAfterInterfaceId) }}
                  </div>
                </el-form-item>
              </template>
            </template>
          </div>
        </el-form>
        <div class="close-btn flex-center" @click="drawerVisible = false">
          <el-icon>
            <CloseBold />
          </el-icon>
        </div>
      </el-drawer>
    </div>
    <el-dialog
      v-model="interfaceVisible"
      :title="`${interfaceType === 'before' ? '前置接口' : '后置接口'}`"
      width="55%"
      top="4%"
      @close="handleInterfaceVisibleClose"
    >
      <SearchBar :search-config="afterInterfaceSearchConfig" @search="handleInterfaceSearch" />
      <el-button
        class="mt-3 mb-2"
        type="primary"
        plain
        @click="handleInterfaceClearSelect"
      >
        清空选择
        <el-icon class="ml-1">
          <Delete />
        </el-icon>
      </el-button>
      <vxe-grid
        ref="interfaceTable"
        :row-config="{
          keyField: 'interfaceId',
        }"
        :pager-config="interfacePagerConfig"
        :data="interfaceTableData"
        :columns="interfaceTableColumns"
        @radio-change="handleAfterInterfaceRadioChange"
        @page-change="handleInterfaceTablePageChange"
      />
      <template #footer>
        <el-button type="primary" @click="handleSureInterface">
          确定
        </el-button>
        <el-button plain type="primary" @click="handleInterfaceVisibleClose">
          关闭
        </el-button>
      </template>
    </el-dialog>
  </div>
</template>

<style lang="scss" scoped>
.node-panel {
  user-select: none;
  position: absolute;
  top: 10px;
  left: 10px;
  width: 70px;
  padding: 20px 10px;
  background-color: white;
  box-shadow: 0 0 10px 1px rgb(228, 224, 219);
  border-radius: 6px;
  text-align: center;
  z-index: 101;
  display: flex;
  flex-direction: column;
  align-items: center;
}

.flow-container {
  height: calc(100vh - 200px);
}

.viewport {
  overflow: hidden;
  position: relative;
  height: 100%;
}

:deep(.flow-add__drawer) {
  .el-drawer__body {
    padding-top: 0;
  }

  .el-drawer__header {
    margin-bottom: 0px;
    padding: 0;
    background: #E8F2FF;

    .dialog-header {
      flex: none;
    }
  }
}

.cm-editor {
  width: 100%;
}

.close-btn {
  position: fixed;
  top: 50%;
  margin-left: -65px;
  cursor: pointer;
  border: none;
  outline: none;
  width: 45px;
  height: 45px;
  font-size: 22px;
  line-height: 40px;
  text-align: center;
  background-color: var(--el-color-primary);
  //border-radius: 5px;
  border-top-left-radius: 5px;
  border-bottom-left-radius: 5px;
  color: #fff;
  box-shadow: 0 0 10px rgba(0, 0, 0, 0.3);

  &:hover {
    background-color: #f56c6c;

    i {
      transition: transform .5s, -webkit-transform .5s;
      transform: rotate(90deg);
    }
  }
}

.business-custom-page {
  background: var(--el-bg-color-page)
}
</style>
